package com.ruoyi.project.module.api.auth.wechat.controller;

import com.ruoyi.project.module.api.auth.wechat.service.WeChatAuthService;
import com.ruoyi.project.module.api.auth.wechat.service.WeChatCoreService;
import com.ruoyi.project.module.api.auth.wechat.utils.WeChatSignUtil;
import com.ruoyi.project.module.api.common.utils.ApiResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.Map;

/**
 * 微信公众号登录
 * @author Javen
 */
@RestController
@RequestMapping("/api/auth/wechat")
@Api("微信登录接口")
public class WeChatController {

    private static Logger logger = LoggerFactory.getLogger(WeChatController.class);

    @Autowired
    WeChatCoreService weChatCoreService;

    @Autowired
    WeChatAuthService weChatAuthService;

    /**
     * 验证服务器地址的有效性
     * @param signature
     * @param timestamp
     * @param nonce
     * @param echostr
     * @param response
     */
    @RequestMapping(value = "/checkIn",method = RequestMethod.GET)
    public void checkSignature(@RequestParam("signature") String signature, @RequestParam("timestamp") String timestamp,
            @RequestParam("nonce") String nonce, @RequestParam("echostr") String echostr, HttpServletResponse response){
        boolean flag = WeChatSignUtil.checkSignature(signature, timestamp, nonce);
        try {
            PrintWriter out = response.getWriter();
            if(flag){
                out.print(echostr);
            }
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 处理微信回传消息
     * @param request
     * @param response
     */
    @RequestMapping(value = "/checkIn",method = RequestMethod.POST)
    public void dealMessageFromWeChat(HttpServletRequest request, HttpServletResponse response) {
        logger.info("----------------开始处理微信发过来的消息------------------");
        // 微信服务器POST消息时用的是UTF-8编码，在接收时也要用同样的编码，否则中文会乱码；
        try {
            request.setCharacterEncoding("UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        // 在响应消息（回复消息给用户）时，也将编码方式设置为UTF-8，原理同上；
        response.setCharacterEncoding("UTF-8");
        response.setHeader("Content-Type", "application/xml");
        String respXml = weChatCoreService.weixinMessageHandelCoreService(request,response);
        if (StringUtils.isBlank(respXml)){
            logger.error("-------------处理微信消息失败-----------------------");
        }else {
            logger.info("----------返回微信消息处理结果-----------------------");
            PrintWriter out = null;
            try {
                out = response.getWriter();
                out.print(respXml);
            } catch (IOException e) {
                e.printStackTrace();
            }finally {
                assert out != null;
                out.close();
            }
        }
    }

    /**
     * 获得登录二维码
     * @param sceneStr
     * @return
     */
    @RequestMapping(value = "/getLoginCode",method = RequestMethod.GET)
    @ApiOperation("获得登录二维码")
    public ApiResult getLoginCode(@RequestParam(value = "sceneStr",required = false) String sceneStr){
        Map<String, Object> loginCodeMap = weChatAuthService.createQrCode(sceneStr);
        return ApiResult.ok(loginCodeMap);
    }

    /**
     * 二维码登录
     * @param sceneStr
     * @return
     */
    @RequestMapping(value = "/login",method = RequestMethod.GET)
    @ApiOperation("二维码登录")
    public ApiResult login(
            @RequestParam(value = "sceneStr") String sceneStr,
            @RequestParam(value = "expires",required = false) Long expires){

        if(null!=expires && System.currentTimeMillis() / 1000 > expires){
            return ApiResult.ok("二维码已过期");
        }

        Map<String, Object> loginMap = weChatAuthService.loginBySceneStr(sceneStr);
        if(null==loginMap){
            return ApiResult.ok("等待扫码...");
        }
        return ApiResult.ok(loginMap);
    }


}
